import wx from './wx'
import qs from 'qs'
import Fly from 'flyio/dist/npm/wx'
import store from '@/store/store'
// var Fly = require('flyio/dist/npm/wx')
const request = new Fly()
var cookie = ''
request.config.withCredentials = true
request.config.timeout = 120 * 1000

request.interceptors.request.use((request) => {
  if (request.method === 'POST' || request.method === 'post') {
    request.body = qs.stringify(request.body)
  }
  request.headers['Cookie'] = store.state.cookie
  wx.showLoading({ title: '加载中...' })
  return request
})

request.interceptors.response.use(
  (response, promise) => {
    console.log(response)
    if (response.request.url === 'apii/accounts/oplogin' || response.request.url === 'apii/accounts/opoauthaccount') {
      cookie = response.headers['set-cookie']
      store.commit('setCookie', cookie)
      console.log(cookie)
    }
    wx.hideLoading()
    if (response.data.code !== 200) {
      var msg = ''
      switch (parseInt(response.data.code)) {
        case 4318:
          msg = '短信认证失败'
          break
        default:
          msg = response.data.message
          break
      }
      wx.showToast({
        title: msg,
        icon: 'none'
      })
    }
    return promise.resolve(response.data)
  },
  (err, promise) => {
    wx.hideLoading()
    wx.showToast({
      title: err.message,
      icon: 'none'
    })
    return promise.resolve()
  }
)

export default request
